﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IO;
using System.Data;


//导出excel用到
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.SS.Util;

namespace SmartExporter
{
    /// <summary>
    /// 日期：2022年3月25日
    /// 类名：Excel帮助类
    /// 说明：进行了简单封装
    /// </summary>
    public class ExportExcelHelper
    {
        private string fileName = null; //文件名
        private IWorkbook workbook = null;
        private FileStream fs = null;
        private bool disposed;

        public ExportExcelHelper(string fileName)
        {
            this.fileName = fileName;
            disposed = false;
        }

        /// <summary>
        /// 将DataTable数据导入到excel中
        /// </summary>
        /// <param name="data">要导入的数据</param>
        /// <param name="isColumnWritten">DataTable的列名是否要导入</param>
        /// <param name="sheetName">要导入的excel的sheet的名称</param>
        /// <returns>导入数据行数(包含列名那一行)</returns>
        public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
        {
            int i = 0;
            int j = 0;
            int count = 0;
            ISheet sheet = null;

            fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                workbook = new XSSFWorkbook();
            else if (fileName.IndexOf(".xls") > 0) // 2003版本
                workbook = new HSSFWorkbook();

            try
            {
                if (workbook != null)
                {
                    sheet = workbook.CreateSheet(sheetName);
                }
                else
                {
                    return -1;
                }

                if (isColumnWritten == true) //写入DataTable的列名
                {
                    IRow row = sheet.CreateRow(0);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
                    }
                    count = 1;
                }
                else
                {
                    count = 0;
                }

                for (i = 0; i < data.Rows.Count; ++i)
                {
                    IRow row = sheet.CreateRow(count);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
                    }
                    ++count;
                }
                workbook.Write(fs); //写入到excel
                return count;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return -1;
            }
        }


        /// <summary>
        /// 导出数据到模板Exccel里
        /// </summary>
        /// <param name="excelTemplatePath">模板路径：--模板为.xls类型的Excel</param>
        /// <param name="exportExcelPath">导出路径</param>
        /// <param name="data">严格对应模板展示数据列顺序的DataTable</param>
        /// <param name="sheetName">模板所在的Sheet工作薄</param>
        /// <param name="startRow">除去表头的数据起始行</param>
        /// <returns>是否成功</returns>
        public bool DataTableToTemplateExcel(string excelTemplatePath, string exportExcelPath, DataTable data, string sheetName, int startRow, string strDepartmentName)
        {
            try
            {
                FileStream file = new FileStream(excelTemplatePath, FileMode.Open, FileAccess.Read);
                HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);
                file.Close();
                HSSFSheet ws = (HSSFSheet)hssfworkbook.GetSheet(sheetName);
                hssfworkbook.FirstVisibleTab = 0;//默认显示第一个工作薄Sheet1
                                                 //公共样式：加边框
                NPOI.SS.UserModel.ICellStyle style = hssfworkbook.CreateCellStyle();

                style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                style.Alignment = HorizontalAlignment.Center;
                for (int i = 0; i < data.Rows.Count; i++)
                {
                    IRow row = ws.CreateRow(i + startRow);
                    for (int j = 0; j < data.Columns.Count; ++j)
                    {
                        var cell = row.CreateCell(j);
                        row.GetCell(j).SetCellValue(data.Rows[i][j].ToString());

                        cell.CellStyle = style;
                    }
                }
                //处理表头的动车所：
                HSSFCellStyle cs_Title = (HSSFCellStyle)hssfworkbook.CreateCellStyle(); //创建列头样式

                #region 设置单位
                IFont font = hssfworkbook.CreateFont();//创建字体
                font.FontHeightInPoints = 14;
                font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold;
                font.FontName = "宋体";
                ws.GetRow(1).GetCell(3).CellStyle.SetFont(font);
                ws.GetRow(1).GetCell(3).SetCellValue("南京动车段" + strDepartmentName);
                #endregion

                //保存到导出路径
                ws.ForceFormulaRecalculation = true;
                FileStream files = new FileStream(exportExcelPath, FileMode.Create);
                hssfworkbook.Write(files);
                files.Close();
                return true;
            }
            catch (Exception ec)
            {
                return false;
            }
        }



        public ISheet GetSheet(string sheetName)
        {
            ISheet sheet = null;
            DataTable data = new DataTable();
            int startRow = 0;

            fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                workbook = new XSSFWorkbook(fs);
            else if (fileName.IndexOf(".xls") > 0) // 2003版本
                workbook = new HSSFWorkbook(fs);

            if (sheetName != null)
            {
                sheet = workbook.GetSheet(sheetName);
                if (sheet == null) //如果没有找到指定的sheetName对应的sheet，则尝试获取第一个sheet
                {
                    sheet = workbook.GetSheetAt(0);
                }
            }
            else
            {
                sheet = workbook.GetSheetAt(0);
            }
            fs.Close();
            return sheet;
        }



        /// <summary>
        /// 将excel中的数据导入到DataTable中
        /// </summary>
        /// <param name="sheetName">excel工作薄sheet的名称</param>
        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
        /// <returns>返回的DataTable</returns>
        public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
        {
            ISheet sheet = null;
            DataTable data = new DataTable();
            int startRow = 0;
            try
            {
                sheet = GetSheet(sheetName);
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    if (isFirstRowColumn)
                    {
                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                            ICell cell = firstRow.GetCell(i);
                            if (cell != null)
                            {
                                string cellValue = cell.StringCellValue;
                                if (cellValue != null)
                                {
                                    DataColumn column = new DataColumn(cellValue);
                                    data.Columns.Add(column);
                                }
                            }
                        }
                        startRow = sheet.FirstRowNum + 1;
                    }
                    else
                    {
                        startRow = sheet.FirstRowNum;
                    }

                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        //修改：yzk 日期：2019-12-10 目的:改为出现空行就截止跳转break不再循环检查下一行
                        if (row == null) break; //没有数据的行默认是null　
                        //if (row == null) continue; //没有数据的行默认是null　　　　　　　

                        DataRow dataRow = data.NewRow();
                        //yzk 2019-12-10 解决获取到行数据不为null，但单元格为空的情况
                        if (row.FirstCellNum == -1) break;
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            //if (row.GetCell(j) != null) //同理，没有数据的单元格都默认是null
                            //{
                            //    if(row.GetCell(j).)
                            //    dataRow[j] = row.GetCell(j).ToString();
                            //}

                            dataRow[j] = GetCellValue(row.GetCell(j));



                        }
                        data.Rows.Add(dataRow);
                    }
                }

                return data;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return null;
            }
        }



        /// <summary>
        /// 将excel中的数据导入到DataTable中
        /// </summary>
        /// <param name="sheetName">excel工作薄sheet的名称</param>
        /// <param name="TitleRowIndex">标题所在行索引，注意起始是0</param>
        /// <returns>返回的DataTable</returns>
        public DataTable ExcelToDataTable(string sheetName, int TitleRowIndex)
        {
            ISheet sheet = null;
            DataTable data = new DataTable();
            int startRow = 0;
            try
            {
                sheet = GetSheet(sheetName);
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(TitleRowIndex);
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    if (TitleRowIndex > 0)
                    {
                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                            ICell cell = firstRow.GetCell(i);
                            if (cell != null)
                            {
                                string cellValue = cell.StringCellValue;
                                if (cellValue != null)
                                {
                                    DataColumn column = new DataColumn(cellValue);
                                    data.Columns.Add(column);
                                }
                            }
                        }
                        startRow = sheet.FirstRowNum + TitleRowIndex + 1;
                    }
                    else
                    {
                        startRow = sheet.FirstRowNum;
                    }

                    //最后一行的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        //修改：yzk 日期：2019-12-10 目的:改为出现空行就截止跳转break不再循环检查下一行
                        if (row == null) break; //没有数据的行默认是null　　　　　　　
                        //if (row == null) continue; //没有数据的行默认是null　(旧的写法)
                        DataRow dataRow = data.NewRow();
                        //yzk 2019-12-10 解决获取到行数据不为null，但单元格为空的情况
                        if (row.FirstCellNum == -1) break;
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            dataRow[j] = GetCellValue(row.GetCell(j));
                        }
                        data.Rows.Add(dataRow);
                    }
                }

                return data;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 将excel中的数据导入到DataTable中,去掉无效的行，无效的列（通过行列为空进行判断）no invalid rows or columns
        /// </summary>
        /// <param name="sheetName">excel工作薄sheet的名称</param>
        /// <param name="TitleRowIndex">标题所在行索引，注意起始是0</param>
        /// <returns>返回的DataTable</returns>
        public DataTable ExcelToDataTableNoInvalidRowsColumns(string sheetName, int TitleRowIndex)
        {
            ISheet sheet = null;
            DataTable data = new DataTable();
            int startRow = 0;
            try
            {
                sheet = GetSheet(sheetName);
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(TitleRowIndex);

                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    if (TitleRowIndex > 0)
                    {
                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                            ICell cell = firstRow.GetCell(i);
                            if (cell != null)
                            {
                                string cellValue = cell.StringCellValue;
                                if (!string.IsNullOrEmpty(cellValue))
                                {
                                    DataColumn column = new DataColumn(cellValue);
                                    data.Columns.Add(column);
                                }
                                else//列名为空说明为最后一列
                                {
                                    cellCount = i;//最后一列的cell编号，即总的列数
                                    break;
                                }
                            }
                        }
                        startRow = sheet.FirstRowNum + TitleRowIndex + 1;
                    }
                    else
                    {
                        startRow = sheet.FirstRowNum;
                    }

                    //最后一行的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) break; //没有数据的行直接退出说明到行尾了

                        DataRow dataRow = data.NewRow();
                        if (row.FirstCellNum == -1) break;
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            ICell cell = row.GetCell(0);
                            if (cell != null)
                            {
                                //每一行的第一列如果为空则直接退出来，说明到最后一行了
                                if (string.IsNullOrEmpty(GetCellValue(cell).ToString()))
                                {
                                    break;
                                }
                            }
                            else
                            {
                                break;
                            }
                            dataRow[j] = GetCellValue(row.GetCell(j));
                        }
                        data.Rows.Add(dataRow);
                    }
                }

                return data;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return null;
            }
        }


        public static object GetCellValue(ICell cell)
        {
            // ICell cell = row.GetCell(j);
            if (cell == null)
                return null;

            switch (cell.CellType)
            {

                case NPOI.SS.UserModel.CellType.Blank: //BLANK:  
                    return null;
                case NPOI.SS.UserModel.CellType.Boolean: //BOOLEAN:  
                    return cell.BooleanCellValue;
                case NPOI.SS.UserModel.CellType.Numeric: //NUMERIC:  
                    short format = cell.CellStyle.DataFormat;
                    if (format != 0) { return cell.DateCellValue; } else { return cell.NumericCellValue; }
                case NPOI.SS.UserModel.CellType.String: //STRING:  
                    return cell.StringCellValue;
                case NPOI.SS.UserModel.CellType.Error: //ERROR:  
                    return cell.ErrorCellValue;
                case NPOI.SS.UserModel.CellType.Formula: //FORMULA:  
                default:
                    return "=" + cell.CellFormula;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    if (fs != null)
                        fs.Close();
                }

                fs = null;
                disposed = true;
            }
        }

        /// <summary>
        /// 作者：YangZhike
        /// 创建日期：2019-8-29
        /// 描述：将数据导入到指定路径下的文件里
        /// </summary>
        /// <param name="excelTemplatePath"></param>
        /// <param name="exportExcelPath"></param>
        /// <param name="data"></param>
        /// <param name="sheetName"></param>
        /// <param name="startRow"></param>
        /// <param name="strDepartmentName"></param>
        /// <returns></returns>
        public bool DataTableToPathExcel(string excelTemplatePath, string exportExcelPath, DataTable data, string sheetName)
        {
            try
            {
                FileStream file = new FileStream(excelTemplatePath, FileMode.Open, FileAccess.Read);
                HSSFWorkbook hssfworkbook = new HSSFWorkbook(file);
                file.Close();
                HSSFSheet ws = (HSSFSheet)hssfworkbook.GetSheet(sheetName);
                hssfworkbook.FirstVisibleTab = 0;//默认显示第一个工作薄Sheet1
                //处理列头
                IRow rowFirst = ws.CreateRow(0);
                for (int i = 0; i < data.Columns.Count; i++)
                {
                    rowFirst.CreateCell(i);
                    rowFirst.GetCell(i).SetCellValue(data.Columns[i].ColumnName);
                }
                //处理行数据
                for (int i = 0; i < data.Rows.Count; i++)
                {
                    IRow row = ws.CreateRow(i + 1);
                    for (int j = 0; j < data.Columns.Count; ++j)
                    {
                        row.CreateCell(j);
                        row.GetCell(j).SetCellValue(data.Rows[i][j].ToString());
                    }
                }
                //保存到导出路径
                ws.ForceFormulaRecalculation = true;
                FileStream files = new FileStream(exportExcelPath, FileMode.Create);
                hssfworkbook.Write(files);
                files.Close();
                return true;
            }
            catch (Exception ec)
            {
                return false;
            }
        }


        #region 最新的导出excel文件
        /// <summary>
        /// 导出称重数据
        /// </summary>
        /// <param name="UserName">操作员</param>
        /// <param name="Plate">车牌号</param>
        /// <param name="GoodsID">物资规格ID</param>
        /// <param name="InOrOut">出库入库</param>
        /// <param name="DeviceID">设备ID</param>
        /// <param name="Driver">司机</param>
        /// <param name="BeginTime">开始时间</param>
        /// <param name="EndTime">结束时间</param>
        /// <returns></returns>
        public static bool ToExcel(string filePath, DataTable dtTemp)
        {
            try
            {
                HSSFWorkbook workbook = new HSSFWorkbook();

                HSSFCellStyle cellStyle = (HSSFCellStyle)workbook.CreateCellStyle();
                HSSFCellStyle cellStyle1 = (HSSFCellStyle)workbook.CreateCellStyle();

                //设置字体
                HSSFFont font = (HSSFFont)workbook.CreateFont();
                font.FontName = "宋体";
                font.FontHeightInPoints = 11;
                cellStyle.SetFont(font);

                HSSFFont font1 = (HSSFFont)workbook.CreateFont();
                font1.FontName = "华文楷体";
                font1.FontHeightInPoints = 16;
                cellStyle1.SetFont(font1);
                //样式设置
                //cellStyle.SetVerticalAlignment((short)HorizontalAlignment.Center); // 居中
                //cellStyle.SetVerticalAlignment((short)VerticalAlignment.Center); //垂直
                cellStyle.Alignment = HorizontalAlignment.Center;
                cellStyle1.Alignment = HorizontalAlignment.Center;

                //再加上日期
                //设置列宽 --赤峰云铜出入厂司机制卡信息统计表
                HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet("赤峰云铜出入厂司机制卡信息统计表");
                sheet.SetColumnWidth(0, 1000);
                sheet.SetColumnWidth(1, 3000);
                sheet.SetColumnWidth(2, 2000);
                sheet.SetColumnWidth(3, 2000);
                sheet.SetColumnWidth(4, 4000);
                sheet.SetColumnWidth(5, 4000);
                sheet.SetColumnWidth(6, 4000);
                sheet.SetColumnWidth(7, 4000);
                sheet.SetColumnWidth(8, 6000);
                sheet.SetColumnWidth(9, 8000);
                sheet.SetColumnWidth(10, 6000);

                //第一行
                CellRangeAddress region = new CellRangeAddress(0, 0, 0, 10);
                sheet.AddMergedRegion(region);
                IRow row0 = sheet.CreateRow(0);
                var cell0 = row0.CreateCell(0);//第2列
                cell0.SetCellValue("赤峰云铜外来人员检测登记台帐（保安大队）");
                row0.GetCell(0).CellStyle = cellStyle1;
                //第二行
                //IRow row1 = sheet.CreateRow(1);
                //var cell_1 = row1.CreateCell(0);
                //var cell_2 = row1.CreateCell(4);
                //cell_1.SetCellValue("开始时间");
                //cell_2.SetCellValue("截止时间");
                //row1.GetCell(0).CellStyle = cellStyle;

                IRow header = sheet.CreateRow(1);
                header.CreateCell(0).SetCellValue("序号");
                header.CreateCell(1).SetCellValue("姓名");
                header.CreateCell(2).SetCellValue("性别");
                header.CreateCell(3).SetCellValue("年龄");
                header.CreateCell(4).SetCellValue("车牌号"); 
                header.CreateCell(5).SetCellValue("运输货物");
                //header.CreateCell(6).SetCellValue("详细家庭住址（市、县、乡镇街道、村（社区）、组（小区）、门牌号等");                
                header.CreateCell(6).SetCellValue("家庭住址");                
                header.CreateCell(7).SetCellValue("联系电话");
                header.CreateCell(8).SetCellValue("进厂时间");
                header.CreateCell(9).SetCellValue("身份证号");
                header.CreateCell(10).SetCellValue("出厂时间");
                header.GetCell(0).CellStyle = cellStyle;
                header.GetCell(1).CellStyle = cellStyle;
                header.GetCell(2).CellStyle = cellStyle;
                header.GetCell(3).CellStyle = cellStyle;
                header.GetCell(4).CellStyle = cellStyle;
                header.GetCell(5).CellStyle = cellStyle;
                header.GetCell(6).CellStyle = cellStyle;
                header.GetCell(7).CellStyle = cellStyle;
                header.GetCell(8).CellStyle = cellStyle;
                header.GetCell(9).CellStyle = cellStyle;
                header.GetCell(10).CellStyle = cellStyle;

                for (int i = 0; i < dtTemp.Rows.Count; i++)
                {
                    IRow row = sheet.CreateRow(i + 2);
                    row.CreateCell(0).SetCellValue(dtTemp.Rows[i]["xu_hao"].ToString());
                    row.CreateCell(1).SetCellValue(dtTemp.Rows[i]["xing_ming"].ToString());
                    row.CreateCell(2).SetCellValue(dtTemp.Rows[i]["xing_bie"].ToString());
                    row.CreateCell(3).SetCellValue(dtTemp.Rows[i]["nian_ling"].ToString());
                    row.CreateCell(4).SetCellValue(dtTemp.Rows[i]["che_hao"].ToString());
                    row.CreateCell(5).SetCellValue(dtTemp.Rows[i]["huo_wu"].ToString());
                    row.CreateCell(6).SetCellValue(dtTemp.Rows[i]["di_zhi"].ToString());
                    row.CreateCell(7).SetCellValue(dtTemp.Rows[i]["lian_xi_dian_hua"].ToString());
                    row.CreateCell(8).SetCellValue(dtTemp.Rows[i]["jin_chang_shi_jian"].ToString());
                    row.CreateCell(9).SetCellValue(dtTemp.Rows[i]["shen_fen_zheng_hao"].ToString());
                    row.CreateCell(10).SetCellValue(dtTemp.Rows[i]["chu_chang_shi_jian"].ToString());
                    row.GetCell(0).CellStyle = cellStyle;
                    row.GetCell(1).CellStyle = cellStyle;
                    row.GetCell(2).CellStyle = cellStyle;
                    row.GetCell(3).CellStyle = cellStyle;
                    row.GetCell(4).CellStyle = cellStyle;
                    row.GetCell(5).CellStyle = cellStyle;
                    row.GetCell(6).CellStyle = cellStyle;
                    row.GetCell(7).CellStyle = cellStyle;
                    row.GetCell(8).CellStyle = cellStyle;
                    row.GetCell(9).CellStyle = cellStyle;
                    row.GetCell(10).CellStyle = cellStyle;
                }
                string fileName = "赤峰云铜外来人员检测登记台帐" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
                //string filePathWhith = Path.Combine(filePath, fileName);
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    workbook.Write(memoryStream);
                    FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write);
                    memoryStream.WriteTo(fileStream);
                    fileStream.Close();
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
                //return Json(new { FileName = "", Code = "Error", Message = "导出失败:" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }
        #endregion

    }
}
